package com.w.utils.spring.context;
/**
 *
 **/

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.BeanFactoryAnnotationUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @Author weiwei
 * @Date 2021-03-01 15:21
 * @description springcontext
 **/
@Component
public class SpringApplicationContext implements ApplicationContextAware {


    private static ApplicationContext applicationContext;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringApplicationContext.applicationContext = applicationContext;
    }

    public static <T> T getBean(Class<T> clazz, String name) {
        return applicationContext.getBean(name, clazz);
    }

    /**
     * 可获取非spring管理的bean
     * @param clazz
     * @param qualified
     * @param <T>
     * @return
     */
    public static <T> T qualifiedBeanOfType(Class<T> clazz, String qualified) {
        return BeanFactoryAnnotationUtils.qualifiedBeanOfType(
                applicationContext.getAutowireCapableBeanFactory(), clazz, qualified);
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
}
